package com.itheima.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/*
 * 工具类
 * */
public class MapperUtil {
    private static SqlSession session = null;

    //私有化构造方法
    private MapperUtil() {
    }

    //获取session
    public static SqlSession getSession() {
        try {
            //读取外部资源
            InputStream is = Resources.getResourceAsStream("sqlConfig.xml");
            //构建sqlseesionfactory对象
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
            //获取SQLsession对象
            session = factory.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return session;
    }

    //释放资源
    public static void close(SqlSession session) {
        //提交事务
        session.commit();
        //释放资源
        session.close();
    }
}
